package com.steel.yfmall.cloud.assistant.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.steel.yfmall.cloud.assistant.oms.mapper.MasterOrderAddressInfoMapper;
import com.steel.yfmall.cloud.assistant.oms.mapper.MasterOrderGoodsMapper;
import com.steel.yfmall.cloud.assistant.oms.mapper.MasterOrderInfoExtendMapper;
import com.steel.yfmall.cloud.assistant.oms.mapper.MasterOrderInfoMapper;
import com.steel.yfmall.cloud.assistant.po.goods.ProductSellerGoods;
import com.steel.yfmall.cloud.assistant.po.goods.ProductSellerGoodsExample;
import com.steel.yfmall.cloud.assistant.po.oms.*;
import com.steel.yfmall.cloud.assistant.po.view.OrderPushCosmicBean;
import com.steel.yfmall.cloud.assistant.utils.HttpSendUtil;
import com.steel.yfmall.cloud.assistant.utils.kd.CosmicLoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * @program: OrderPushCongqiongListener
 * @author: liuzhijun
 * @date: 2021-03-24 14:56
 **/
@Slf4j
@Component
public class OrderPushCangQiongListener {


    @Value("${ds_cosmic_orderdetail_url}")
    private String DS_COSMIC_ORDERDETAIL_URL;


    @Value("${ds_cosmic_ordercancel_url}")
    private String DS_COSMIC_ORDERCANCEL_URL;

    @Resource
    private MasterOrderInfoMapper masterOrderInfoMapper;
    @Resource
    private MasterOrderAddressInfoMapper masterOrderAddressInfoMapper;
    @Resource
    private MasterOrderInfoExtendMapper masterOrderInfoExtendMapper;
    @Resource
    private MasterOrderGoodsMapper masterOrderGoodsMapper;

    @JmsListener(destination = "order_push_cq_listener_debug")
    public void doOrderPushCangQiongSync(String onMsgText) {
        OrderPushCosmicBean paraBean = null;
        try {


            if (log.isDebugEnabled()) {
                log.info("OrderPushCangQiongListener  doOrderPushCangQiongSync  order_push_cq_listener: " + onMsgText);
            }
            if (StringUtils.isBlank(onMsgText)) {
                log.error("销售平台订单推送苍穹:参数为空！");
                return;
            }
            paraBean = JSON.parseObject(onMsgText, OrderPushCosmicBean.class);
            if (paraBean == null) {
                log.error("销售平台订单推送苍穹必传参数为空：" + onMsgText);
                return;
            }

            String strOrderNo = paraBean.getYfgt_ecomordercode();
            if (strOrderNo != null && strOrderNo.length() > 0) {
                MasterOrderInfo orderInfo = null;
                MasterOrderInfoExample example = new MasterOrderInfoExample();
                example.createCriteria().andMasterOrderSnEqualTo(strOrderNo);
                orderInfo = masterOrderInfoMapper.selectOneByExampleSelective(example);
                if (orderInfo != null) {
                    String strErr = "";

                    MasterOrderAddressInfo addressInfo = null;
                    try {
                        MasterOrderAddressInfoExample exampleS = new MasterOrderAddressInfoExample();
                        exampleS.createCriteria().andMasterOrderSnEqualTo(strOrderNo);
                        addressInfo = masterOrderAddressInfoMapper.selectOneByExampleSelective(exampleS);
                    } catch (Exception exx) {
                        log.error("销售平台订单推送苍穹失败: " + onMsgText + " 地址信息获取失败" + exx.getMessage());
                    }

                    MasterOrderInfoExtend addressInfoExtend = null;
                    try {
                        MasterOrderInfoExtendExample exampleS = new MasterOrderInfoExtendExample();
                        exampleS.createCriteria().andMasterOrderSnEqualTo(strOrderNo);
                        addressInfoExtend = masterOrderInfoExtendMapper.selectOneByExampleSelective(exampleS);
                    } catch (Exception exx) {
                        log.error("销售平台订单推送苍穹失败: " + onMsgText + " 扩展信息获取失败" + exx.getMessage());
                    }
                    MasterOrderGoodsExample goodsExample = new MasterOrderGoodsExample();
                    goodsExample.createCriteria().andMasterOrderSnEqualTo(strOrderNo);
                    List<MasterOrderGoods> goodsInfos = masterOrderGoodsMapper.selectByExample(goodsExample);
                    MasterOrderGoods masterOrderGoods = goodsInfos.get(0);

                    JSONObject bill = new JSONObject();
                    JSONArray billentry = new JSONArray();
                    JSONArray recplanentry = new JSONArray();
//            yfgt_ecomordercod	 单据编号
                    bill.put("yfgt_ecomordercode", orderInfo.getMasterOrderSn());
//            billtype	单据类型	String
                    bill.put("billtype", "");
//            biztype	业务类型	String
                    bill.put("biztype", "");
//            bizdate	订单日期	Date
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                    bill.put("bizdate", dateFormat.format(orderInfo.getCreateTime()));
//            billstatus	单据状态	String
                    bill.put("billstatus", "A");
//            yfgt_procategorie	产品大类	String
                    bill.put("yfgt_procategorie", orderInfo.getProductTypeNo().substring(0,1));
//            yfgt_ordergoods	订货方式	String
                    bill.put("yfgt_ordergoods", "");
//            yfgt_salemonth	销售月份	date
                    bill.put("yfgt_salemonth", dateFormat.format(orderInfo.getCreateTime()));
//            yfgt_saletype	销售方式	String
                    bill.put("yfgt_saletype", "");
                    if (addressInfo != null) {
                        //  yfgt_destination	终到地点	String
                        bill.put("yfgt_destination", addressInfo.getLocaleCode());
                        //            yfgt_disarea	终到区域	String\
                        bill.put("yfgt_disarea", addressInfo.getFinishAreaCode());
                        //            yfgt_traffictype	运输方式	String
                        bill.put("yfgt_traffictype", addressInfo.getCartCode());
                    }

//            comment	备注	String
                    if (addressInfoExtend != null) {
                        bill.put("comment", addressInfoExtend.getRemark() != null ? addressInfoExtend.getRemark() : "");
                    }
//            yfgt_weighttype	计重方式	String
                    bill.put("yfgt_weighttype", "");
//            yfgt_balancetype	结算方式	String
                    bill.put("yfgt_balancetype", orderInfo.getSettlementType() != null ? orderInfo.getSettlementType() : "");

                    bill.put("yfgt_balancetype","sm1");//测试用，需要修改～～～～～～～～～
//            yfgt_freightpayment	运费支付方式	String
                    bill.put("yfgt_freightpayment", orderInfo.getSettlementTicket());


//                    销售信息
//            payingcustomer	付款方	String
                    bill.put("payingcustomer", orderInfo.getCompanyName());
//            customer	客户	String
                    bill.put("customer", orderInfo.getUserName());
//            address	联系地址	String
                    bill.put("address", addressInfo.getAddress());
//            linkman	联系人	String
//                    bill.put("linkman", orderInfo.getUserName());
//            linkmanphone	联系人电话	String
                    bill.put("linkmanphone", addressInfo.getMobile());
//            receiveaddress	收货地址	String
                    bill.put("receiveaddress", addressInfo.getAddress());
//            reccustomer	收货方	String
                    bill.put("reccustomer", orderInfo.getUserName());
//            yfgt_end_user	最终用户	String
                    bill.put("yfgt_end_user", orderInfo.getUserName());
//            reclinkman	收货联系人	String
                    bill.put("yfgt_reclinkman", orderInfo.getUserName());
//            settlecustomer	收票方	String
                    bill.put("settlecustomer", "");
//            dept	销售部门	String
                    bill.put("dept", "");
//            operator	销售员	String
                    bill.put("operator", "");
//            operatorgroup	销售组	String
                    bill.put("operatorgroup", "");
//            org	销售组织	String
                    bill.put("org", masterOrderGoods.getBrandCode()+"00000000");
//                    财务信息
//            currency	本位币	String
                    bill.put("currency", "CNY");
//            paymode	付款方式	String
                    bill.put("paymode", "CASH");
//            istax	含税	String
                    bill.put("istax", orderInfo.getTotalFee());
//            exchangerate	汇率	String
                    bill.put("exchangerate", "1");
//            exratetable	汇率表	String
                    bill.put("exratetable", "ERT-01");
//            exratedate	汇率日期	date
                    bill.put("exratedate", dateFormat.format(orderInfo.getCreateTime()));
//            totalallamount	价税合计	String
                    bill.put("totalallamount", "");
//            settlecurrency	结算币别	String
                    bill.put("settlecurrency", "CNY");
//            settletype	结算方式	String
                    bill.put("settletype", "");
//            totalamount	金额	BigDecimal
                    bill.put("totalamount", orderInfo.getTotalFee());
//            receiptamount	累计收款金额	BigDecimal
                    bill.put("receiptamount", "");
//            prereceiptamount	累计预收款金额	BigDecimal
                    bill.put("prereceiptamount", "");
//            reccondition	收款条件	String
                    bill.put("reccondition", "");
//            totaltaxamount	税额	String
                    bill.put("totaltaxamount", "");
//              yfgt_carrier_type 承运方式
                    bill.put("yfgt_carrier_type", orderInfo.getTypeOfCarriage());
//            yfgt_pay_number  运费付款账户
                    bill.put("yfgt_pay_number", orderInfo.getAccountNumber());
//  ├         yfgt_destination_city 字符串 否 是 目的地城市
                    bill.put("yfgt_destination_city", "上海");
                //详细地址
                    bill.put("yfgt_detailed_address",addressInfo.getAddress());
                    //定向物流公司名称
                    bill.put("yfgt_company_name","顺丰");

                    //定向车辆
                    bill.put("yfgt_carnumber","皖a bbb");

                    bill.put("yfgt_goal_county","顺丰");

                    bill.put("yfgt_is_include_tax","1");


                    //  ├ yfgt_detailed_address 字符串 否 是 目的地详细地址
                    //├ yfgt_company_name 字符串 否 是 物流公司名称
                    //├ yfgt_goal_county 字符串 否 是 目的地县
                    //├ yfgt_is_include_tax 字符串 否 是 是否含税价

//            订单明细-物料明细

                    if (goodsInfos != null) {
                        for (MasterOrderGoods goodsInfo : goodsInfos) {
                            JSONObject entry = new JSONObject();
//            materialmasterid	物料	String
//                            entry.put("materialmasterid", "");
//            material	物料编码	String
//                            entry.put("material", "");
//            materialnamep	物料名称	String
//                            entry.put("materialnamep", "");
//            model	规格型号	String
//                            entry.put("model", "");
//            materialversion	物料版本	String
//                            entry.put("materialversion", "");
//            auxpty	辅助属性	String
//                            entry.put("auxpty", "");
//            yfgt_roductform	产品形态	String


                            entry.put("yfgt_roductform", goodsInfo.getProductTypeNo());
//            yfgt_id_card	 牌号
                            entry.put("yfgt_id_card", goodsInfo.getProductTradeno());
//            yfgt_reservedate	预定交期	String
                            entry.put("yfgt_reservedate", dateFormat.format(orderInfo.getCreateTime()));
//            yfgt_deliverydate	发货日期	String
                            entry.put("yfgt_deliverydate", dateFormat.format(orderInfo.getCreateTime()));
//            yfgt_qualitytype	品质分类	String
                            entry.put("yfgt_qualitytype", "");
//            yfgt_size	尺寸信息	String
                            entry.put("yfgt_size", goodsInfo.getProductSizeMsg());
//            yfgt_iswater	是否穿水	String
                            entry.put("yfgt_iswater", goodsInfo.getCraft());
//            yfgt_factory	厂区	String
                            entry.put("yfgt_factory", goodsInfo.getBrandCode());
//            yfgt_basedatafield1	库区	String
                            entry.put("yfgt_stockplace", goodsInfo.getDepotCode());
//            yfgt_type	大小件	String
                            entry.put("yfgt_type", goodsInfo.getSizePieces());
//            yfgt_change_level	是否降级	String
                            entry.put("yfgt_change_level", goodsInfo.getIsDowngrade());
//            yfgt_colcr	颜色名称	String
                            entry.put("yfgt_colcr", goodsInfo.getColor());
//            yfgt_diameter	直径（mm）	String
                            entry.put("yfgt_diameter", goodsInfo.getProductThick());
//            yfgt_length	长度（mm）	String
                            entry.put("yfgt_length", goodsInfo.getProductLen());
//            yfgt_packages	件数	String
                            entry.put("yfgt_packages", "");
//            unit	计量单位	String
                            entry.put("unit", "t");
//            qty	订货量	String
                            entry.put("qty", goodsInfo.getSendWeight());
//            baseunit	基本单位	String
                            entry.put("baseunit", "");
//            baseqty	基本数量	String
                            entry.put("baseqty", "");
//            auxunit	辅助单位	String
                            entry.put("auxunit", "");
//            auxqty	辅助数量	String
                            entry.put("auxqty", "");
//            price	单价	String
                            entry.put("price", goodsInfo.getTransactionUnitPrice());
//            priceandtax	含税单价	String
                            entry.put("priceandtax", goodsInfo.getTransactionUnitPrice());
//            taxrate	税率(%)	String
                            entry.put("taxrate", "");
//                    srcbillnumber 源合同号
                            entry.put("srcbillnumber", "");
// srcbillentryseq 字符串 源合同行号
                            entry.put("srcbillentryseq", "");
                            billentry.add(entry);
//

//            订单明细-收款计划
//            r_itemname	款项名称	String
//            r_recadvancerate	应收比率(%)	String
//            r_recadvanceamount	应收金额	String
//            r_needrecadvance	是否预收	String
//            r_remainamount	关联收款金额	String
//            r_recamount	实收金额	String
//            r_relbillno	关联单号	String
//            r_recsettleorg	结算组织	String
//            r_controlsend	控制环节	String
//            recentrychangetype	变更方式	String
                        }
                    } else {
                        strErr += "商品明细获取失败";
                    }
                    bill.put("billentry", billentry);
                    bill.put("recplanentry",recplanentry);
//                    bill.put("yfgt_ecomordercode", "XSDD-210331-000003");
                    String apptoken = CosmicLoginUtil.GetAPPToken();
                    String accessToken = CosmicLoginUtil.getAccessToken(apptoken);
                    String url = DS_COSMIC_ORDERDETAIL_URL + "?access_token=" + accessToken;
                    JSONObject semdData = new JSONObject();
                    semdData.put("bill", bill);
                    log.info(JSON.toJSONString(bill));
                    String result = HttpSendUtil.sendPost(url, JSONObject.toJSONString(semdData));
                    try {
                        JSONObject re = JSONObject.parseObject(result);
                    } catch (Exception ex) {
                        log.error("销售平台订单推送苍穹失败: 返回结果转换json失败 结果为：[" + result + "] " + onMsgText, ex);
                    }

                } else {
                    log.error("销售平台订单推送苍穹失败: " + onMsgText + " 订单不存在");
                }
            } else {
                log.error("销售平台订单推送苍穹失败: " + onMsgText + " 订单号不能为空");
            }
        } catch (Exception e) {
            log.error("销售平台订单推送苍穹失败: " + onMsgText, e);
        }
    }


    @JmsListener(destination = "order_cancel_push_cq_listener")
    public void doCancelOrderPushCangQiongSync(String onMsgText) {
        OrderPushCosmicBean paraBean = null;
        try {
            if (log.isDebugEnabled()) {
                log.info("order_cancel_push_cq_listener  doCancelOrderPushCangQiongSync : " + onMsgText);
            }
            if (StringUtils.isBlank(onMsgText)) {
                log.error("销售平台取消订单推送苍穹:参数为空！");
                return;
            }
            paraBean = JSON.parseObject(onMsgText, OrderPushCosmicBean.class);
            if (StringUtils.isBlank(paraBean.getYfgt_ecomordercode())) {
                log.error("销售平台取消订单推送苍穹失败: " + onMsgText + "  销售订单号不能为空");
                return;
            }

            String result = "";
            String url = "";
            try {
                //获取登录token
                String accessToken = CosmicLoginUtil.getAccessToken(CosmicLoginUtil.GetAPPToken());
                url = DS_COSMIC_ORDERCANCEL_URL + "?access_token=" + accessToken;
                String str = "";
                JSONObject obj = new JSONObject();
                obj.put("yfgt_ecomordercode", paraBean.getYfgt_ecomordercode());
                obj.put("org", "yf");
                str = obj.toString();
                result = CosmicLoginUtil.GetHttpMsg(str, url);
            } catch (Exception e) {
                log.error("请求url异常:" + url);
            }
            JSONObject jsonObject = JSON.parseObject(result);
            Boolean bool = (Boolean) jsonObject.get("success");
            if (bool) {
                log.info("销售平台取消订单推送苍穹成功: " + result);
            } else {
                log.error("销售平台取消订单推送苍穹失败: " + result);
            }
        } catch (Exception e) {
            log.error("销售平台取消订单推送苍穹失败: " + onMsgText, e);
        }
    }

}
